/**
 * 厨房服务类 - 管理厨房和菜品数据
 */

// 初始化云环境
const db = () => wx.cloud.database();
const kitchenCollection = () => db().collection('mykichen');
const dishCollection = () => db().collection('mydishes');
const myfavoritesCollection = () => db().collection('myfavorites');

const userService = require('./userService');

// 存储键名 - 仅用于缓存
const STORAGE_KEYS = {
  DEFAULT_KITCHEN: 'defaultKitchen'
};

// 初始化默认数据
const initKitchens = async () => {
  console.log('初始化厨房数据');
  
  // 获取当前用户ID
  const userId = userService.getCurrentUserId();
  if (!userId) {
    console.error('未找到用户ID，无法初始化厨房数据');
    return [];
  }
  
  const defaultKitchen = {
    name: '我的甜蜜小厨',
    description: '健康美味，从这里开始',
    image: '/imgs/kitchen.avif',
    dishCount: 3,
    viewCount: 0,
    isDefault: true,
    userId: userId,
    createTime: db().serverDate()
  };
  
  // 添加默认厨房数据
  try {
    const res = await kitchenCollection().add({
      data: defaultKitchen
    });
    
    const kitchenId = res._id;
    
    // 设置默认厨房
    wx.setStorageSync(STORAGE_KEYS.DEFAULT_KITCHEN, kitchenId);
    
    // 初始化对应的菜品数据
    await initDishes(userId, kitchenId);
    
    return { ...defaultKitchen, _id: kitchenId };
  } catch (error) {
    console.error('初始化厨房数据失败', error);
    return null;
  }
};

// 初始化默认菜品数据
const initDishes = async (userId, kitchenId) => {
  console.log('初始化菜品数据');
  
  if (!userId || !kitchenId) {
    console.error('未找到用户ID或厨房ID，无法初始化菜品数据');
    return [];
  }
  
  const defaultDishes = [
      {
        name: '蔬菜沙拉',
        description: '新鲜蔬菜搭配特制沙拉酱',
        image: 'cloud://cloud1-6gjewz7jf1fbf260.636c-cloud1-6gjewz7jf1fbf260-1309982001/dishes/1745855918461.jpg',
        tags: ['快手菜', '家常菜', '甜点'],
        price: 1.0,
        kitchenId: kitchenId,
        userId: userId,
        createTime: db().serverDate(),
        calories: 123.0,
        cookingTime: 123.0,
        difficulty: '简单',
        nutrition: {
            carbs: 123.0,
            fat: 123.0,
            fiber: 123.0,
            protein: 123.0
        },
        isFavorite: false
    },
    {
      name: '红烧肉',
      description: '传统美食，肥而不腻',
      image: '/imgs/hsr.avif',
      tags: ['家常菜', '美味', '下饭'],
      price: 36,
      kitchenId: kitchenId,
      userId: userId,
      createTime: db().serverDate()
    },
    {
      name: '披萨',
      description: '派对必备美食',
      image: '/imgs/chef-hat.svg',
      tags: ['派对', '西餐', '分享'],
      price: 45,
      kitchenId: kitchenId,
      userId: userId,
      createTime: db().serverDate()
    }
  ];
  
  // 添加默认菜品数据
  try {
    for (const dish of defaultDishes) {
      await dishCollection().add({
        data: dish
      });
    }
    return defaultDishes;
  } catch (error) {
    console.error('初始化菜品数据失败', error);
    return [];
  }
};

/**
 * 获取所有厨房列表
 */
const getAllKitchens = async () => {
  try {
    // 获取当前用户ID
    const userId = userService.getCurrentUserId();
    if (!userId) {
      console.error('未找到用户ID，无法获取厨房列表');
      return [];
    }
    
    // 检查该用户的厨房数据是否存在
    const { total } = await kitchenCollection().where({ userId: userId }).count();
    
    // 如果没有厨房数据，初始化默认数据
    if (total === 0) {
      return await initKitchens();
    }
    
    // 获取当前用户的所有厨房数据
    const { data: kitchens } = await kitchenCollection()
      .where({ userId: userId })
      .orderBy('createTime', 'desc')
      .get();

    // 获取每个厨房在Share表中的点赞数据
    const kitchenIds = kitchens.map(k => k._id);
    
    // 获取Share表中的点赞数据
    const { data: shareData } = await db().collection('Share')
      .where({
        kitchenId: db().command.in(kitchenIds),
        type: 'topic'
      })
      .get();

    // 将点赞数据添加到厨房数据中
    const enrichedKitchens = kitchens.map(kitchen => {
      const shareInfo = shareData.find(s => s.kitchenId === kitchen._id) || {};
      return {
        ...kitchen,
        likeCount: shareInfo.likeCount || 0
      };
    });
    
    return enrichedKitchens;
  } catch (error) {
    console.error('获取厨房列表失败', error);
    return [];
  }
};

/**
 * 获取厨房详情
 * @param {string} id 厨房ID
 */
const getKitchenById = async (id) => {
  if (!id) return null;
  
  try {
    const userId = userService.getCurrentUserId();
    const { data } = await kitchenCollection().doc(id).get();
    
    // 验证厨房是否属于当前用户
    if (data && data.userId === userId) {
      return data;
    }
    return null;
  } catch (error) {
    console.error(`获取厨房(${id})详情失败`, error);
    return null;
  }
};

/**
 * 获取默认厨房
 */
const getDefaultKitchen = async () => {
  // 获取当前用户ID
  const userId = userService.getCurrentUserId();
  if (!userId) {
    console.error('未找到用户ID，无法获取默认厨房');
    return null;
  }

  // 从本地缓存获取默认厨房ID
  let defaultKitchenId = wx.getStorageSync(STORAGE_KEYS.DEFAULT_KITCHEN);
  
  // 查询当前用户的所有厨房
  const kitchens = await getAllKitchens();
  
  // 如果本地没有记录默认厨房或ID无效，则查找isDefault为true的厨房
  if (!defaultKitchenId || !kitchens.some(k => k._id === defaultKitchenId)) {
    const defaultKitchen = kitchens.find(k => k.isDefault);
    
    if (defaultKitchen) {
      defaultKitchenId = defaultKitchen._id;
      wx.setStorageSync(STORAGE_KEYS.DEFAULT_KITCHEN, defaultKitchenId);
    } else if (kitchens.length > 0) {
      // 如果没有默认厨房，使用第一个厨房
      defaultKitchenId = kitchens[0]._id;
      wx.setStorageSync(STORAGE_KEYS.DEFAULT_KITCHEN, defaultKitchenId);
    } else {
      return null;
    }
  }
  
  return await getKitchenById(defaultKitchenId);
};

/**
 * 设置默认厨房
 * @param {string} kitchenId 厨房ID
 */
const setDefaultKitchen = async (kitchenId) => {
  // 获取当前用户ID
  const userId = userService.getCurrentUserId();
  if (!userId) {
    console.error('未找到用户ID，无法设置默认厨房');
    return false;
  }

  // 验证厨房ID是否存在
  const kitchen = await getKitchenById(kitchenId);
  if (!kitchen) {
    return false;
  }
  
  try {
    // 更新当前用户所有厨房的isDefault字段为false
    await kitchenCollection().where({
      userId: userId,
      isDefault: true
    }).update({
      data: {
        isDefault: false
      }
    });
    
    // 将指定厨房设为默认
    await kitchenCollection().doc(kitchenId).update({
      data: {
        isDefault: true
      }
    });
    
    // 更新本地缓存
    wx.setStorageSync(STORAGE_KEYS.DEFAULT_KITCHEN, kitchenId);
    return true;
  } catch (error) {
    console.error(`设置默认厨房(${kitchenId})失败`, error);
    return false;
  }
};

/**
 * 保存厨房信息
 * @param {Object} kitchen 厨房对象
 */
const saveKitchen = async (kitchen) => {
  if (!kitchen) return false;
  
  // 获取当前用户ID
  const userId = userService.getCurrentUserId();
  if (!userId) {
    console.error('未找到用户ID，无法保存厨房');
    return false;
  }
  
  try {
    // 获取该厨房的菜品数量
    let dishCount = 0;
    if (kitchen._id) {
      const countResult = await dishCollection().where({
        kitchenId: kitchen._id,
        userId: userId
      }).count();
      dishCount = countResult.total;
    }
    
    if (kitchen._id) {
      // 验证厨房是否属于当前用户
      const existingKitchen = await getKitchenById(kitchen._id);
      if (!existingKitchen || existingKitchen.userId !== userId) {
        console.error('无权修改该厨房');
        return false;
      }
      
      // 更新现有厨房
      await kitchenCollection().doc(kitchen._id).update({
        data: {
          name: kitchen.name,
          description: kitchen.description,
          image: kitchen.image,
          dishCount: dishCount,
          updateTime: db().serverDate()
        }
      });
    } else {
      // 添加新厨房
      const kitchenData = {
        name: kitchen.name,
        description: kitchen.description,
        image: kitchen.image || '/imgs/chef-hat.svg',
        dishCount: 0,
        viewCount: 0,
        isDefault: false,
        userId: userId,
        createTime: db().serverDate()
      };
      
      const res = await kitchenCollection().add({
        data: kitchenData
      });
      
      // 返回新创建的厨房ID
      kitchen._id = res._id;
    }
    
    return true;
  } catch (error) {
    console.error('保存厨房信息失败', error);
    return false;
  }
};

/**
 * 删除厨房
 * @param {string} kitchenId 厨房ID
 */
const deleteKitchen = async (kitchenId) => {
  if (!kitchenId) return false;
  
  // 获取当前用户ID
  const userId = userService.getCurrentUserId();
  if (!userId) {
    console.error('未找到用户ID，无法删除厨房');
    return false;
  }
  
  try {
    const kitchen = await getKitchenById(kitchenId);
    if (!kitchen) {
      return false;
    }
    
    // 验证厨房是否属于当前用户
    if (kitchen.userId !== userId) {
      console.error('无权删除该厨房');
      return false;
    }
    
    // 如果删除的是默认厨房，需要重新设置默认厨房
    if (kitchen.isDefault) {
      // 查找该用户的其他厨房
      const { data: otherKitchens } = await kitchenCollection().where({
        userId: userId,
        _id: db().command.neq(kitchenId)
      }).get();
      
      // 如果还有其他厨房，将第一个设为默认
      if (otherKitchens.length > 0) {
        await setDefaultKitchen(otherKitchens[0]._id);
      }
    }
    
    // 删除厨房下的所有菜品
    await dishCollection().where({
      kitchenId: kitchenId,
      userId: userId
    }).remove();
    
    // 删除厨房
    await kitchenCollection().doc(kitchenId).remove();
    
    return true;
  } catch (error) {
    console.error(`删除厨房(${kitchenId})失败`, error);
    return false;
  }
};

/**
 * 获取特定厨房的菜品列表
 * @param {string} kitchenId 厨房ID
 */
const getDishesForKitchen = async (kitchenId) => {
  if (!kitchenId) return [];
  
  // 获取当前用户ID
  const userId = userService.getCurrentUserId();
  if (!userId) {
    console.error('未找到用户ID，无法获取菜品');
    return [];
  }
  
  try {
    const { data: dishes } = await dishCollection()
      .where({
        kitchenId: kitchenId,
        userId: userId
      })
      .orderBy('createTime', 'desc')
      .get();
    
    return dishes;
  } catch (error) {
    console.error(`获取厨房(${kitchenId})的菜品失败`, error);
    return [];
  }
};

/**
 * 获取菜品详情
 * @param {string} kitchenId 厨房ID
 * @param {string} dishId 菜品ID
 */
const getDishById = async (kitchenId, dishId) => {
  if (!kitchenId || !dishId) return null;
  
  // 获取当前用户ID
  const userId = userService.getCurrentUserId();
  if (!userId) {
    console.error('未找到用户ID，无法获取菜品详情');
    return null;
  }
  
  try {
    const { data } = await dishCollection().doc(dishId).get();
    
    // 验证菜品是否属于当前用户和指定厨房
    if (data && data.kitchenId === kitchenId && data.userId === userId) {
      return data;
    }
    return null;
  } catch (error) {
    console.error(`获取菜品(${dishId})详情失败`, error);
    return null;
  }
};

/**
 * 保存菜品（新增或更新）
 * @param {string} kitchenId 厨房ID
 * @param {object} dishData 菜品数据
 */
const saveDish = async (kitchenId, dishData) => {
  try {
    // 获取当前用户ID
    const userId = userService.getCurrentUserId();
    if (!userId) {
      console.error('未找到用户ID，无法保存菜品');
      return false;
    }

    // 检查厨房是否存在
    const kitchen = await getKitchenById(kitchenId);
    if (!kitchen) {
      console.error('厨房不存在');
      return false;
    }

    // 如果是编辑模式
    if (dishData.id) {
      const { id, data } = dishData;
      // 确保添加必要的字段
      const updateData = {
        ...data,
        kitchenId,
        userId,
        updateTime: db().serverDate()
      };

      // 更新菜品
      await dishCollection().doc(id).update({
        data: updateData
      });
    } else {
      // 新增模式
      // 确保添加必要的字段
      const newDishData = {
        ...dishData,
        kitchenId,
        userId,
        createTime: db().serverDate(),
        updateTime: db().serverDate()
      };

      // 添加新菜品
      await dishCollection().add({
        data: newDishData
      });
    }

    return true;
  } catch (error) {
    console.error('保存菜品失败:', error);
    return false;
  }
};

/**
 * 删除菜品
 * @param {string} kitchenId 厨房ID
 * @param {string} dishId 菜品ID
 */
const deleteDish = async (kitchenId, dishId) => {
  if (!kitchenId || !dishId) return false;
  
  // 获取当前用户ID
  const userId = userService.getCurrentUserId();
  if (!userId) {
    console.error('未找到用户ID，无法删除菜品');
    return false;
  }
  
  try {
    // 验证菜品是否存在且属于当前用户
    const dish = await getDishById(kitchenId, dishId);
    if (!dish) {
      return false;
    }
    
    // 删除菜品
    await dishCollection().doc(dishId).remove();
    
    // 更新厨房的菜品数量
    const countResult = await dishCollection().where({
      kitchenId: kitchenId,
      userId: userId
    }).count();
    
    await kitchenCollection().doc(kitchenId).update({
      data: {
        dishCount: countResult.total
      }
    });
    
    return true;
  } catch (error) {
    console.error(`删除菜品(${dishId})失败`, error);
    return false;
  }
};

/**
 * 获取当前用户的厨房数量
 */
const getKitchenCount = async () => {
  // 获取当前用户ID
  const userId = userService.getCurrentUserId();
  if (!userId) {
    console.error('未找到用户ID，无法获取厨房数量');
    return 0;
  }
  
  try {
    const countResult = await kitchenCollection().where({
      userId: userId
    }).count();
    
    return countResult.total || 0;
  } catch (error) {
    console.error('获取厨房数量失败', error);
    return 0;
  }
};

/**
 * 获取当前用户的收藏数量
 */
const getFavoriteavoriteCount = async () => {
   // 获取当前用户ID
   const userId = userService.getCurrentUserId();
   if (!userId) {
     console.error('未找到用户ID，无法获取收藏数量');
     return 0;
   }
   console.log(userId);
   try {
     const countResult = await myfavoritesCollection().where({
       userId: userId
     }).count();
     console.log(countResult);
     return countResult.total || 0;
   } catch (error) {
     console.error('获取收藏数量失败', error);
     return 0;
   }
};

/**
 * 获取当前用户的菜品数量
 */
const getDishCount = async () => {
  // 获取当前用户ID
  const userId = userService.getCurrentUserId();
  if (!userId) {
    console.error('未找到用户ID，无法获取菜品数量');
    return 0;
  }
  
  try {
    const countResult = await dishCollection().where({
      userId: userId
    }).count();
    
    return countResult.total || 0;
  } catch (error) {
    console.error('获取菜品数量失败', error);
    return 0;
  }
};

/**
 * 分享厨房到专题
 * @param {Object} params 分享参数
 * @param {string} params.kitchenId 厨房ID
 * @param {Array<string>} params.tags 专题标签数组，可选
 */
const shareKitchenToTopic = async (params) => {
  try {
    const { kitchenId, tags = ['分享厨房'] } = params;
    if (!kitchenId) {
      throw new Error('参数不完整');
    }

    // 获取当前用户信息
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo || !userInfo._id) {
      throw new Error('请先登录');
    }

    // 检查是否已经分享过
    const { total } = await db().collection('Share').where({
      userId: userInfo._id,
      kitchenId: kitchenId,
      type: 'topic'
    }).count();

    if (total > 0) {
      throw new Error('您已分享过此厨房到专题');
    }

    // 获取厨房信息
    const kitchen = await getKitchenById(kitchenId);
    if (!kitchen) {
      throw new Error('未找到厨房信息');
    }

    // 创建分享记录
    await db().collection('Share').add({
      data: {
        userId: userInfo._id,
        userName: userInfo.nickname,
        userAvatar: userInfo.avatarUrl,
        kitchenId: kitchenId,
        type: 'topic',
        tags: tags,
        shareTime: db().serverDate(),
        kitchenName: kitchen.name,
        kitchenImage: kitchen.image,
        kitchenDescription: kitchen.description,
        dishCount: kitchen.dishCount || 0,
      }
    });

    return { success: true };
  } catch (error) {
    console.error('分享到专题失败:', error);
    return { 
      success: false, 
      message: error.message || '分享失败'
    };
  }
};

// 导出方法
module.exports = {
  // 厨房相关
  getAllKitchens,
  getKitchenById,
  getDefaultKitchen,
  setDefaultKitchen,
  saveKitchen,
  deleteKitchen,
  
  // 菜品相关
  getDishesForKitchen,
  getDishById,
  saveDish,
  deleteDish,
  
  // 其他相关
  getKitchenCount,
  getDishCount,
  getFavoriteavoriteCount,
  shareKitchenToTopic,
}; 